//封装axios
import axios from "axios";

//创建axios的实例
const service = axios.create({
   baseURL: "http://localhost:8080",
   timeout: 60000
});

//添加请求拦截器
service.interceptors.request.use(config =>{
    console.log("请求拦截器被执行");
    console.log(config);
    //每次发送请求时需要携带token
    let token = sessionStorage.getItem("token");
    //将token绑定到请求头中， 后端能够获取到
    config.headers['token'] = token;
    // config.headers['token'] = "111";
    return config;
},error =>{
    console.log(error);
    return Promise.reject(error);
});
//添加响应拦截器

service.interceptors.response.use(response =>{
    console.log("响应拦截器被执行");
    console.log(response);
    //如果token被篡改，那么请求应该失败
    if(response.data.state == false){
        //证明token是无效的
        window.location.href= '/login';
    }else {
        return response;
    }

},error =>{
    console.log(error);
    return Promise.reject(error);
});
//导出axios的实例模块
export default service;